package com.qq.filter;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qq.oauth.Config;
import com.qq.oauth.Token;
import com.qq.util.ParseString;

public class ConnectFilter implements Filter {

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		//PrintWriter out = response.getWriter();
		String appid = Config.APP_ID ;
		String appkey = Config.APP_KEY;
		String oauth_callback = Config.OAUTH_CALLBACK;
		String redirect_url = "http://openapi.qzone.qq.com/oauth/qzoneoauth_authorize?oauth_consumer_key="+appid;
		//request token
		Token token = new Token();
		String request_token = token.getRequestToken(appid, appkey);
		//out.println(request_token);
		HashMap<String, String> tokens = ParseString.ParseTokenString(request_token);
		String oauth_token = tokens.get("oauth_token");
		//out.println(oauth_token);
		String oauth_token_secret = tokens.get("oauth_token_secret");
		//out.println(oauth_token_secret);
		request.getSession().setAttribute("oauth_token_secret", oauth_token_secret);
		redirect_url += "&oauth_token="+oauth_token;
		redirect_url += "&oauth_callback="+URLEncoder.encode(oauth_callback);
		//out.println(redirect_url);
		response.sendRedirect(redirect_url);
		
	}

	public void init(FilterConfig arg0) throws ServletException {

	}

	public void destroy() {

	}

}
